package com.xy.shop.web.service.impl;

import com.xy.shop.common.constant.AppConstants;
import com.xy.shop.common.constant.CommonContants;
import com.xy.shop.common.constant.Rst;
import com.xy.shop.common.utils.EncryptUtil;
import com.xy.shop.web.dao.ApplyOrderMapper;
import com.xy.shop.web.dao.WxUserMapper;
import com.xy.shop.web.entity.ApplyOrder;
import com.xy.shop.web.entity.WxUser;
import com.xy.shop.web.service.ApplyOrderService;
import com.xy.shop.web.service.BaseParamService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ApplyOrderServiceImpl implements ApplyOrderService {
    @Resource
    private ApplyOrderMapper applyOrderMapper;

    @Resource
    private WxUserMapper tWxUserMapper;

    @Resource
    private BaseParamService baseParamService;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public int deleteByPrimaryKey(String orderId) {
        return applyOrderMapper.deleteByPrimaryKey(orderId);
    }

    @Override
    public int insert(ApplyOrder record) {
        return applyOrderMapper.insert(record);
    }

    @Override
    public ApplyOrder selectByPrimaryKey(String orderId) {
        return applyOrderMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public List<ApplyOrder> selectAll() {
        return applyOrderMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(ApplyOrder record) {
        return applyOrderMapper.updateByPrimaryKey(record);
    }

    @Override
    public Map<String, Object> order(ApplyOrder order) {
        if (StringUtils.isBlank(order.getKey()) && order.getKey().length() < 5) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE, "签密异常！");
        }
        if (StringUtils.isBlank(order.getCompany()) || StringUtils.isBlank(order.getTaobaoId()) || Double.parseDouble(order.getMoney().toString()) < 0) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_1003, "请按照要求填写资料！");
        }
       String sing= (String) redisTemplate.opsForValue().get(AppConstants.RedisKey.ORDER_WRITE_SING+order.getKey());
        if(StringUtils.isBlank(sing)) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_1002, "签名参数失效，请公众号输入，“填单”！");
        }
      //  String key = order.getKey().substring(5, order.getKey().length());
        String idAndOpenId = EncryptUtil.decrypt(sing);
        if (idAndOpenId.equals(CommonContants.ERROR)) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_1002, "非法秘钥！");
        }
        if (idAndOpenId.indexOf("@") < 0) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_1002, "非法秘钥！");
        }
        String str[] = idAndOpenId.split("@");
        order.setVxId(str[0]);
        order.setOpenId(str[1]);
        order.setCtime(new Date());
        WxUser tWxUser = tWxUserMapper.selectByPrimaryKey(Integer.valueOf(str[0]));
        if (Objects.isNull(tWxUser)) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_1004, "暂无当前用户！");
        }
        if (!tWxUser.getOpenId().equals(str[1])) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_1005, "用户信息不一致！");
        }
        ApplyOrder applyOrder = this.selectByPrimaryKey(order.getOrderId());
        if (Objects.nonNull(applyOrder)) {
            return Rst.getReturnData(null, false, CommonContants.FAILURE_1006, "订单已存在！");
        }
        int count = this.insert(order);
        if (count > 0) {
            return Rst.getReturnData(order, true, CommonContants.FAILURE_SUCCESS, "提交成功！");
        } else {
            return Rst.getReturnData(order, false, CommonContants.FAILURE_1003, "订单入库异常！");
        }
    }

    @Override
    public List<Map<String, Object>> selectOrderList(Map<String, Object> param) {
        return applyOrderMapper.selectOrderList(param);
    }

    /**
     * @ClassName ApplyOrderServiceImpl
     * @Description : 功能说明 随机字符串无效(前五位)，后部分参数为加密后参数，解密时前五位不参与解密
     * @Param:
     * @Return :
     * @Author : zyy
     * @Date : 2020/6/25 23:28
    */
    @Override
    public String getOrderWriteUrl(String openId, String userId) {
         String random=EncryptUtil.randomStr(5);
            String data= userId+"@"+openId;
            try {
                data =	EncryptUtil.encrypt(data);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        return  ASCIISort(random+data);
    }
    public static String ASCIISort(String str) {
        char[] test = new char[str.length()];
        StringBuilder sb = new StringBuilder();
        while (true) {
            String a = str;//直接读取这行当中的字符串。
            for (int i = 0; i < str.length(); i++) {
                //字符串处理每次读取一位。
                test[i] = a.charAt(i);
            }
            Arrays.sort(test);
            for (int i = 0; i < test.length; i++) {
                sb.append(test[i]);
            }
            String trim = sb.toString().trim();
            return trim;
        }
    }
    public static void main(String[] args) throws Throwable {
        System.out.println(EncryptUtil.encrypt("1@opVHItzcVjYd_1yIItRxPMB3Q2-U"));
        System.out.println( ASCIISort(EncryptUtil.encrypt("1@opVHItzcVjYd_1yIItRxPMB3Q2-U")));
    }
}
